from flask import Blueprint, request, jsonify, render_template
from app.models.db import get_db
from flask_login import login_required  # 新增
stock_docs_bp = Blueprint('stock_docs', __name__)

# 单据列表页面
@stock_docs_bp.route('/stock/docs')
def stock_docs_page():
    return render_template('stock_docs.html')

# 单据详情页面
@stock_docs_bp.route('/stock/docs/<doc_id>')
def stock_doc_detail_page(doc_id):
    return render_template('stock_doc_detail.html')

# 获取单据列表（带/api前缀）
@stock_docs_bp.route('/api/stock/docs', methods=['GET'])
@login_required
def get_stock_docs():
    doc_type = request.args.get('doc_type', '')
    warehouse = request.args.get('warehouse', '')
    cursor = get_db().cursor()
    query = "SELECT * FROM stock_doc WHERE 1=1"
    params = []
    if doc_type:
        query += " AND doc_type=?"
        params.append("入库" if doc_type == "IN" else "出库")
    if warehouse:
        query += " AND warehouse=?"
        params.append(warehouse)
    query += " ORDER BY create_time DESC"
    cursor.execute(query, params)
    return jsonify([dict(row) for row in cursor.fetchall()])

# 获取单据详情（带/api前缀）
@stock_docs_bp.route('/api/stock/docs/<doc_id>', methods=['GET'])
@login_required
def get_stock_doc_detail(doc_id):
    cursor = get_db().cursor()
    cursor.execute("SELECT * FROM stock_doc WHERE doc_id=?", (doc_id,))
    doc_row = cursor.fetchone()
    if not doc_row:
        return jsonify({'status': 'error', 'message': '单据不存在'}), 404
    cursor.execute("SELECT * FROM stock_doc_item WHERE doc_id=?", (doc_id,))
    items = [dict(row) for row in cursor.fetchall()]
    return jsonify({'doc': dict(doc_row), 'items': items})